//模块
const express = require('express');
const bodyParser = require('body-parser');
const SQLQuery = require('./utils/query.js');
let jwt = require('./utils/JWT.js');
let common = require('./utils/common.js');

var app = express();
global.common = common;


app.use(bodyParser.urlencoded({ extended: false })); //parse application/x-www-form-urlencoded
app.use(bodyParser.json()); //parse application/json
// app.use(express.static(__dirname + '/public/web'));
app.use(express.static('./public'));
app.use('/admin', express.static('./admin'));


app.all("*", (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");// 跨域处理
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    res.set('Cache-Control', 'no-cache');
    next(); // 执行下一个路由
})

app.use((req, res, next) => {
    if (req.url.indexOf('/api/upload') != -1 || req.url === "/api/adminLogin/login" || req.url.indexOf('/client/') != -1 || req.url.indexOf('/mini/') != -1) {
        next()
        return;
    }

    //如果有token就验证，没token就通过
    const token = req.headers["authorization"]?.split(" ")[1]
    if (token) {
        let payload = jwt.verify(token)
        //验证成功就生成一个新token重置有效时间，验证失败就返回错误码让前端跳到登录页
        if (payload) {
            const newToken = jwt.generate({
                id: payload.id,
                username: payload.username
            }, "1h")
            res.header("Authorization", newToken);
            next();
            return;
        } else {
            res.status(401).send({ code: "-1", message: "token过期" })
            return;
        }
    } else {
        res.status(401).send({ code: "-1", message: "未登录" })
        return;
    }
})

// 路由模块
app.use('/api/visit', require('./routers/visit'));//埋点
app.use('/api/adminLogin', require('./routers/adminAccount.js'));//管理员用户模块
app.use('/api/feedback', require('./routers/feedback'));//意见反馈
app.use('/api/upload', require('./routers/upload'));//文件上传
app.use('/api/product', require('./routers/product'));//产品模块
app.use('/api/rawMaterial', require('./routers/rawMaterial'));//产品模块

// 小程序
app.use('/api/account', require('./routers/account'));//微信用户
app.use('/api/address', require('./routers/address.js'));//地址
app.use('/api/banner', require('./routers/banner.js'));//banner
app.use('/api/goods', require('./routers/goods.js'));//商品
app.use('/api/cart', require('./routers/cart.js'));//购物车
app.use('/api/order', require('./routers/order.js'));//订单



// 数据库心跳
setInterval(async function () {
    try {
        var sql = 'select * from hb';
        await SQLQuery.query(sql);
    } catch (err) {

    }

}, 3600000)

const PORT = process.env.PORT || 3002;
var server = app.listen(PORT, function () {
    var host = server.address().address
    var port = server.address().port
    console.log(`应用实例，访问地址为 http://%s:%s`, host, port)
})